/*
*  Copyright 2019-2025 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.jiaoyou.likes.rest;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.jiaoyou.chats.domain.Chats;
import me.zhengjie.modules.jiaoyou.likes.domain.Likes;
import me.zhengjie.modules.jiaoyou.likes.service.LikesService;
import me.zhengjie.modules.jiaoyou.likes.domain.dto.LikesQueryCriteria;
import lombok.RequiredArgsConstructor;
import java.util.List;

import me.zhengjie.modules.jiaoyou.moments.domain.Moments;
import me.zhengjie.modules.jiaoyou.moments.mapper.MomentsMapper;
import me.zhengjie.modules.jiaoyou.users.domain.Users;
import me.zhengjie.modules.jiaoyou.users.mapper.UsersMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.PageResult;

/**
* @author ztd
* @date 2025-11-19
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "点赞管理")
@RequestMapping("/api/likes")
public class LikesController {

    private final LikesService likesService;
    private final UsersMapper usersMapper;
    private final MomentsMapper momentsMapper;

    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('likes:list')")
    public void exportLikes(HttpServletResponse response, LikesQueryCriteria criteria) throws IOException {
        likesService.download(likesService.queryAll(criteria), response);
    }

    @GetMapping
    @ApiOperation("查询点赞管理")
    @PreAuthorize("@el.check('likes:list')")
    public ResponseEntity<PageResult<Likes>> queryLikes(LikesQueryCriteria criteria){
        Page<Object> page = new Page<>(criteria.getPage(), criteria.getSize());
        final PageResult<Likes> likesPageResult = likesService.queryAll(criteria, page);
        // 如果内容不为空就查询用户昵称
        final List<Likes> content = likesPageResult.getContent();
        if (CollectionUtil.isNotEmpty(content)) {
            List<Integer> userIdList = content.stream().map(Likes::getUserId).collect(Collectors.toList());
            List<Long> momentsIdList = content.stream().map(Likes::getMomentId).collect(Collectors.toList());
            final List<Users> users = usersMapper.selectBatchIds(userIdList);
            final List<Moments> momentsList = momentsMapper.selectBatchIds(momentsIdList);
            final Map<Integer, Users> usersMap = users.stream().collect(Collectors.toMap(Users::getId, e -> e));
            final Map<Integer, Moments> momentsMap = momentsList.stream().collect(Collectors.toMap(Moments::getId, e -> e));
            for (Likes likes : content) {
                final String targetNickName = Optional.ofNullable(usersMap.get(likes.getUserId())).map(Users::getNickname).orElse(StrUtil.EMPTY);
                final String momentsContent = Optional.ofNullable(momentsMap.get(likes.getMomentId().intValue())).map(Moments::getContent).orElse(StrUtil.EMPTY);
                likes.setUserName(targetNickName);
                likes.setMomentContent(momentsContent);
            }
        }
        return new ResponseEntity<>(likesPageResult,HttpStatus.OK);
    }

    @PostMapping
    @Log("新增点赞管理")
    @ApiOperation("新增点赞管理")
    @PreAuthorize("@el.check('likes:add')")
    public ResponseEntity<Object> createLikes(@Validated @RequestBody Likes resources){
        likesService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改点赞管理")
    @ApiOperation("修改点赞管理")
    @PreAuthorize("@el.check('likes:edit')")
    public ResponseEntity<Object> updateLikes(@Validated @RequestBody Likes resources){
        likesService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除点赞管理")
    @ApiOperation("删除点赞管理")
    @PreAuthorize("@el.check('likes:del')")
    public ResponseEntity<Object> deleteLikes(@ApiParam(value = "传ID数组[]") @RequestBody List<Integer> ids) {
        likesService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}